import React, { forwardRef, useImperativeHandle, useMemo, useRef } from 'react';
import usePickerProps from './hooks/use-picker-props';
import { PickerProps, PickerRef, PickerValue } from './interface';
import PickerColumn, { PickerColumnRef } from './PickerColumn';
import PickerContainer from './PickerContainer';

const Picker = forwardRef<PickerRef, PickerProps>((_props, ref) => {
	const [
		{ optionHeight, visibleOptionsCount, transitionDuration },
		{
			defaultValue,
			data,
			dataNames,
			onChange,
			onConfirm,
			onCancel,
			...restProps
		},
	] = usePickerProps(_props);

	const rootRef = useRef<HTMLDivElement>(null);
	const columnRef = useRef<PickerColumnRef>(null);

	const pickerRef = useMemo<PickerRef>(
		() => ({
			root: rootRef.current,
			getValue: () => {
				const cr = columnRef.current;

				if (cr) {
					return cr.getValue();
				}
			},
		}),
		[],
	);

	useImperativeHandle<PickerRef, PickerRef>(ref, () => pickerRef, [
		pickerRef,
	]);

	const emit = (listener?: (v?: PickerValue) => void) => {
		listener && listener(pickerRef.getValue());
	};

	return (
		<PickerContainer
			{...restProps}
			optionHeight={optionHeight}
			visibleOptionsCount={visibleOptionsCount}
			ref={rootRef}
			onConfirm={() => emit(onConfirm)}
			onCancel={() => emit(onCancel)}
		>
			<PickerColumn
				optionHeight={optionHeight}
				visibleOptionsCount={visibleOptionsCount}
				transitionDuration={transitionDuration}
				defaultValue={defaultValue}
				data={data}
				dataNames={dataNames}
				onChange={onChange}
				ref={columnRef}
			/>
		</PickerContainer>
	);
});

Picker.displayName = 'Picker';

export default Picker;
